package com.goodluck.goodluckim.ui.msg;

import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.goodluck.goodluckim.R;
import com.goodluck.goodluckim.db.model.CSMessage;
import com.goodluck.goodluckim.db.model.IMMessage;
import com.goodluck.goodluckim.sdk.LogUtils;
import com.goodluck.goodluckim.sdk.constant.MsgDirection;
import com.goodluck.goodluckim.sdk.constant.SessionType;
import com.goodluck.goodluckim.sdk.event.MessageEvent;
import com.goodluck.goodluckim.sdk.module.Container;
import com.goodluck.goodluckim.sdk.msg.MessageBuilder;
import com.goodluck.goodluckim.ui.msg.adapter.MessageAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by wyj on 2018/9/13.
 */

public class MessageListPanel {

    private Container container;
    private View rootView;

    private RecyclerView messageListView;
    private SmartRefreshLayout messageRefreshLayout;
    private List<IMMessage> messages;
    private MessageAdapter adapter;
    private Handler uiHandler;

    public MessageListPanel(Container container, View rootView) {
        this.container = container;
        this.rootView = rootView;
        this.uiHandler = new Handler();
        RxBus.get().register(this);
        initListView();
    }

    private void initListView() {
        messages = new ArrayList<>();
        adapter = new MessageAdapter(messages);
        messageRefreshLayout = (SmartRefreshLayout) rootView.findViewById(R.id.message_refreshlayout);
        messageRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            sleep(2000);
                            container.activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    messageRefreshLayout.finishRefresh();
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        messageRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                Log.e("Message", "onLoadMore");
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            sleep(2000);
                            container.activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    messageRefreshLayout.finishLoadMore();
//                                    messageRefreshLayout.finishLoadMoreWithNoMoreData();
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        messageListView = (RecyclerView) rootView.findViewById(R.id.message_rv);
        messageListView.setLayoutManager(new LinearLayoutManager(container.activity));
        messageListView.requestDisallowInterceptTouchEvent(true);
        messageListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState != RecyclerView.SCROLL_STATE_IDLE) {
                    container.proxy.shouldCollapseInputPanel();
                }
            }
        });
        messageListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        messageListView.setAdapter(adapter);

        for (int i = 0; i < 1; i++) {
            CSMessage message;
            if (i % 2 == 0) {
                message = MessageBuilder.createTextMessage(i, "文本消息:asdasd[ebh]asdasds[eca]" + i, SessionType.TEAM);
            } else if (i % 3 == 0) {
                message = MessageBuilder.createTextMessage(i, "文本消息:asdagg[ecq]gdj[eci]fsdfsdf[eex][ecg][deg]" + i, SessionType.TEAM);
            } else {
                message = MessageBuilder.createImageMessage(i, "图片消息:" + i, SessionType.TEAM, null);
            }
            if (i / 5 == 0) {
                message.setMessageDirection(MsgDirection.OUT);
            } else {
                message.setMessageDirection(MsgDirection.IN);
            }
            message.setObjectName("昵称" + i);

            IMMessage imMessage = new IMMessage();
            imMessage.setMessageContent(message.getMessageContent());
            imMessage.setSessionID(message.getSessionID());
            imMessage.setSenderUserId(message.getSenderUserId());
            imMessage.setMessageType(message.getMessageType());
            imMessage.setSendTime(message.getSendTime());
            imMessage.setObjectName(message.getObjectName());
            imMessage.setMessageDirection(message.getMessageDirection());
            messages.add(imMessage);
        }
        adapter.notifyDataSetChanged();
        scrollToBottom();
    }

    @Subscribe(thread = EventThread.NEW_THREAD)
    public void messageEvent(MessageEvent event) {
        LogUtils.printe("接收到消息");
        switch (event.getEventType()) {
            case MessageEvent.EventType.RECEIVE_MESSAGE: {
                final IMMessage message = event.getMessage();
                container.activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.addData(message);
                    }
                });
            }
            break;
            case MessageEvent.EventType.UPDATE_MESSAGE_STATUS: {
                IMMessage message = event.getMessage();
                for (int i = 0; i < messages.size(); i++) {
                    IMMessage updateItem = messages.get(i);
                    if (updateItem.getMessageId() == message.getMessageId()) {
                        updateItem.setSendStatus(updateItem.getSendStatus());
                        final int finalI = i;
                        container.activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.refreshNotifyItemChanged(finalI);
                            }
                        });
                        break;
                    }
                }
            }
            default: {

            }
            break;
        }
    }

    /**
     * 刷新消息列表
     */
    public void refreshMessageList() {
        container.activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    public void scrollToBottom() {
        uiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                doScrollToBottom();
            }
        }, 200);
    }

    /**
     * 自动滚动列表到底部
     */
    private void doScrollToBottom() {
        messageListView.scrollToPosition(
                adapter.getItemCount() - 1);
    }

    /**
     * 发送消息后，更新本地消息列表
     *
     * @param message
     */
    public void onMsgSend(IMMessage message) {
        //todo
        List<IMMessage> addedListItems = new ArrayList<>(1);
        addedListItems.add(message);
        adapter.addData(message);
        doScrollToBottom();
    }

    /**
     * 消息排序
     *
     * @param list
     */
    private void sortMessages(List<IMMessage> list) {
        if (list.size() == 0) {
            return;
        }
        Collections.sort(list, comparator);
    }

    private static Comparator<IMMessage> comparator = new Comparator<IMMessage>() {
        @Override
        public int compare(IMMessage o1, IMMessage o2) {
            long time = o1.getReceivedTime() - o2.getReceivedTime();
            return time == 0 ? 0 : (time < 0 ? -1 : 1);
        }
    };

    /**
     * 页面销毁处理
     */
    public void onDestroy() {
//        registerObservers(false);
        RxBus.get().unregister(this);
    }

    /**
     * 返回的监听
     *
     * @return
     */
    public boolean onBackPressed() {
        uiHandler.removeCallbacks(null);
//        MessageAudioControl.getInstance(container.activity).stopAudio(); // 界面返回，停止语音播放
//        if (voiceTrans != null && voiceTrans.isShow()) {
//            voiceTrans.hide();
//            return true;
//        }
        return false;
    }

    /**
     * 重置数据
     *
     * @param container
     * @param anchor
     */
    public void reload(Container container, IMMessage anchor) {
        this.container = container;
        if (adapter != null) {
            adapter.getData().clear();
            adapter.notifyDataSetChanged();
        }

        for (int i = 0; i < 100; i++) {
            CSMessage message;
            if (i % 2 == 0) {
                message = MessageBuilder.createTextMessage(i, "文本消息:asdasd[ebh]asdasds[eca]" + i, SessionType.TEAM);
            } else if (i % 3 == 0) {
                message = MessageBuilder.createTextMessage(i, "文本消息:asdagg[ecq]gdj[eci]fsdfsdf[eex][ecg][deg]" + i, SessionType.TEAM);
            } else {
                message = MessageBuilder.createImageMessage(i, "图片消息:" + i, SessionType.TEAM, null);
            }
            if (i / 5 == 0) {
                message.setMessageDirection(MsgDirection.OUT);
            } else {
                message.setMessageDirection(MsgDirection.IN);
            }
            message.setObjectName("昵称" + i);

            IMMessage imMessage = new IMMessage();
            imMessage.setMessageContent(message.getMessageContent());
            imMessage.setSessionID(message.getSessionID());
            imMessage.setSenderUserId(message.getSenderUserId());
            imMessage.setMessageType(message.getMessageType());
            imMessage.setSendTime(message.getSendTime());
            imMessage.setObjectName(message.getObjectName());
            imMessage.setMessageDirection(message.getMessageDirection());
            messages.add(imMessage);
        }
        adapter.notifyDataSetChanged();
    }
}
